package com.fredia.terp.aspect;

import java.util.Arrays;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * aop 切面处理
 * 
 * @author : wangyong
 * @since : 2017年6月23日
 * @version : v0.0.1
 */
@Aspect
@Component
@Order(-5)
public class WebLogAspect {
	private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
	ThreadLocal<Long> startTime = new ThreadLocal<>();

	/**
	 * 定义一个切入点. 解释下：
	 */
	@Pointcut("execution(* com.fredia.terp.controller..*.*(..))")
	public void controllerLog() {

	}

	@Before("controllerLog()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		// 统计切片内方法的执行时间

		// 接收到请求，记录请求内容
		logger.info("WebLogAspect.doBefore()");
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		// 记录下请求内容
		logger.info("HTTP_METHOD : " + request.getMethod());
		startTime.set(System.currentTimeMillis());
		// logger.info("CLASS_METHOD : " +
		// joinPoint.getSignature().getDeclaringTypeName() + "."
		// + joinPoint.getSignature().getName());
		// logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
		// // 获取所有参数方法一：
		// Enumeration<String> enu = request.getParameterNames();
		// while (enu.hasMoreElements()) {
		// String paraName = (String) enu.nextElement();
		// System.out.println(paraName + ": " + request.getParameter(paraName));
		// }
	}

	@AfterReturning(returning = "ret", pointcut = "controllerLog()")
	public void doAfterReturning(Object ret) throws Throwable {
		// 处理完请求，返回切片內方法执行时间
		logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
	}

}